package com.zp.game

import android.graphics.Color
import android.graphics.Paint
import android.view.MotionEvent
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.dialogs.ZpParams
import com.helloandroid.dialogs.ZpResultDialog
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.MyLog
import game.engine.base.*

class ZpScene : Scene() {

    companion object {
        const val AngleSpeed = 420f
        const val HbOffsetY = 120f
        const val UsedCountOffsetY = 160f
    }

    lateinit var mBtnHelp: Sprite
    lateinit var mBtnPiece: Sprite
    lateinit var mBtnStart: Sprite
    lateinit var mBtnBack: Sprite
    lateinit var mRestLabel: Label

    lateinit var mSpPanZi: Sprite
    lateinit var mSpLight: Sprite
    lateinit var mProgress: Progress

    lateinit var mHb1: ZpHb
    lateinit var mHb2: ZpHb
    lateinit var mHb5: ZpHb

    // 是否正在转动
    private var bRolling = false

    var zpLottery = ZpLottery()
    var targetDegress = 0f
    var elpasedDegress = 0f

    var lightNum = 0


    // 数据是否准备好
    var isReady = false

    var selectedResult: ZpAwardType? = null

    fun roll(){
        // 产生一个度数,转过去
        selectedResult = zpLottery.genResult()
        targetDegress = selectedResult!!.degress + 1 * 360f
        elpasedDegress = gcdDegress(mSpPanZi.degress)
        bRolling = true
    }

    override fun onTouch(touch: Touch) {

        if (touch.type == MotionEvent.ACTION_DOWN) {

            if (!isReady) {
                return
            }

            // 判断是否可以开始转
            if (!bRolling) {
                val zpGame = Director.instance.gameApp.activity as ZpGame
                val info = zpGame.mInfo!!
                var restCount = 0
                synchronized(info) {
                    restCount = info.resetCount
                }
                val worldRect = transformLocalRectToWorldRect(mBtnStart.parent!!, mBtnStart.getBoundingBox())
                if (worldRect.contains(touch.x, touch.y)) {

                    if (restCount > 8){
                        roll()
                    }else{
                        if (restCount > 0){
                            // 播视频进行旋转
                            zpGame.handler.post {
                                VideoAdUtil.playVideoAd(zpGame){success->
                                    if (success){
                                        Analyse.report(AnalyseKey.Zp_Video)
                                        roll()
                                    }else{
                                        AppUtil.toast("视频还未准备好!")
                                    }
                                }
                            }
                        }else{
                            AppUtil.toast("今日抽奖已达最大值!")
                        }
                    }
                    return
                }
            }

            // 判断哪个按钮被点击了
            // 帮助
            val helpRect = transformLocalRectToWorldRect(mBtnHelp.parent!!, mBtnHelp.getBoundingBox())
            if (helpRect.contains(touch.x, touch.y)) {
                MyLog.elog("help btn clicked!")
                val zpGame = Director.instance.gameApp.activity as ZpGame
                zpGame.handler.post {
                    HelperDialog(zpGame).show()
                }
                return
            }

            // piece(兑换)
            val pieceRect = transformLocalRectToWorldRect(mBtnPiece.parent!!, mBtnPiece.getBoundingBox())
            if (pieceRect.contains(touch.x, touch.y)) {
                MyLog.elog("piece btn clicked!")
                val zpGame = Director.instance.gameApp.activity as ZpGame
                zpGame.handler.post {
                    PiecesDialog(zpGame).show()
                }
                return
            }

            // 返回
            val backRect = transformLocalRectToWorldRect(mBtnBack.parent!!, mBtnBack.getBoundingBox())
            if (backRect.contains(touch.x, touch.y)) {
                // 退出
                Director.instance.gameApp.activity.finish()
                return
            }

            // 下面额外领取的红包
            if (mHb1.isConsumeTouchEvent(touch.x, touch.y)) {
                return
            }
            if (mHb2.isConsumeTouchEvent(touch.x, touch.y)) {
                return
            }
            if (mHb5.isConsumeTouchEvent(touch.x, touch.y)) {
                return
            }
        }
    }

    override fun onEnter() {
        super.onEnter()

        // 显示一个全局的背景
        val director = Director.instance
        val wa = director.windowAdapter
        val graphics = ZpGame.res
        fillBgBitmap = graphics.bgBitmap

        // 标题
        val title = Sprite(bitmap = graphics.titleBitmap)
        title.y = wa.minY + 150f
        addChild(title)

        // 文字
        val textBg = Sprite(bitmap = graphics.textBgBitmap).apply {
            mRestLabel = Label("剩余次数:0次")
            mRestLabel.align = Paint.Align.CENTER
            mRestLabel.textColor = Color.WHITE
            addChild(mRestLabel)
        }
        textBg.y = title.y + 140f
        addChild(textBg)

        // 返回
        mBtnBack = Sprite(bitmap = graphics.backBitmap)
        mBtnBack.x = wa.minX + 100
        mBtnBack.y = wa.minY + 150f
        addChild(mBtnBack)

        // 规则
        mBtnHelp = Sprite(bitmap = graphics.helpBitmap, sx = 1.2f, sy = 1.2f)
        mBtnHelp.x = wa.maxX - 100f
        mBtnHelp.y = wa.minY + 150f
        addChild(mBtnHelp)

        // 兑换
        mBtnPiece = Sprite(bitmap = graphics.pieceBitmap, sx = 1.2f, sy = 1.2f)
        mBtnPiece.x = wa.maxX - 100f
        mBtnPiece.y = mBtnHelp.y + 100f
        addChild(mBtnPiece)

        // 转盘
        val panziBg = Sprite(bitmap = graphics.panziBgBitmap).apply {
            // panzi
            mSpPanZi = Sprite(bitmap = graphics.panziBitmap)
            addChild(mSpPanZi)

            // light
            mSpLight = Sprite(bitmap = graphics.lightBitmap1)
            addChild(mSpLight)

            // btn start
            mBtnStart = Sprite(bitmap = graphics.startBitmap)
            addChild(mBtnStart)
        }
        panziBg.y = -150f
        addChild(panziBg)

        // 额外奖励
        val extraBg = Sprite(bitmap = graphics.extraBgBitmap).apply {
            val label = Label("抽奖次数", Paint.Align.LEFT)
            label.textSize = graphics.bigTextSize
            label.x = -477f
            label.y = 108f
            addChild(label)

            // 进度条
            mProgress = Progress(
                    fgBitmap = graphics.pgFgBitmap,
                    bgBitmap = graphics.pgBgBitmap,
                    percent = 0.0f
            )
            mProgress.x = 100f
            mProgress.y = 108f
            addChild(mProgress)

            // 下面还有3个文字
            // 还需要对齐位置
            // 3个红包
            val pgWorldPos = mProgress.getWorldPos()

            mHb1 = ZpHb(
                    idx = 0,
                    alreadyGetBitmap = graphics.alreadyGetBitmap,
                    activeBitmap = graphics.activeBitmap1,
                    inActiveBitmap = graphics.inActiveBitmap1,
                    targetValue = 5
            )
            addChild(mHb1)
            val tmpPos = transformWorldParentToLocalPos(mHb1.parent!!, pgWorldPos)
            mHb1.y = tmpPos.y - HbOffsetY
            mHb1.x = tmpPos.x - 240f

            mHb2 = ZpHb(
                    idx = 1,
                    alreadyGetBitmap = graphics.alreadyGetBitmap,
                    activeBitmap = graphics.activeBitmap2,
                    inActiveBitmap = graphics.inActiveBitmap2,
                    targetValue = 15
            )
            addChild(mHb2)
            mHb2.x = tmpPos.x
            mHb2.y = tmpPos.y - HbOffsetY

            mHb5 = ZpHb(
                    idx = 2,
                    alreadyGetBitmap = graphics.alreadyGetBitmap,
                    activeBitmap = graphics.activeBitmap5,
                    inActiveBitmap = graphics.inActiveBitmap5,
                    targetValue = 30
            )
            addChild(mHb5)
            mHb5.y = tmpPos.y - HbOffsetY
            mHb5.x = tmpPos.x + 360f - 52f

            //  下面3个文字
            val lbCount5 = Label("5次", Paint.Align.CENTER)
            addChild(lbCount5)
            lbCount5.x = mHb1.x
            lbCount5.y = mHb1.y + UsedCountOffsetY

            val lbCount15 = Label("15次", Paint.Align.CENTER)
            addChild(lbCount15)
            lbCount15.x = mHb2.x
            lbCount15.y = mHb2.y + UsedCountOffsetY

            val lbCount30 = Label("30次", Paint.Align.CENTER)
            addChild(lbCount30)
            lbCount30.x = mHb5.x
            lbCount30.y = mHb5.y + UsedCountOffsetY
        }
        extraBg.y = wa.maxY - 300f
        addChild(extraBg)


        // light效果简单实现
        scheduleCount(0f, Int.MAX_VALUE, 0.4f) {
            if (bRolling) {
                lightNum++
                mSpLight.bitmap = if (lightNum % 2 == 0) ZpGame.res.lightBitmap1 else ZpGame.res.lightBitmap2
            }
        }
    }

    override fun update(dt: Float) {
        if (bRolling) {
            val d = AngleSpeed * dt
            elpasedDegress += d
            if (elpasedDegress >= targetDegress) {
                elpasedDegress = targetDegress
                mSpPanZi.degress = elpasedDegress
                bRolling = false
                MyLog.elog("转动停止......")

                //  更新 Info
                //  更新UI
                val zpAwardType = selectedResult!!
                val zpGame = Director.instance.gameApp.activity as ZpGame
                val info = zpGame.mInfo!!
                synchronized(info) {

                    // 更新本地结果
                    info.increase(zpAwardType.value, zpAwardType.count)

                    // 上报结果
                    AppUtil.appViewModel().zpReportResult(zpAwardType.value, zpAwardType.count)

                    updateUI(info)
                }

                // 显示结果
                zpGame.handler.post {
                    ZpResultDialog(zpGame, ZpParams(zpAwardType.imgResId, zpAwardType.count)).show()
                }
            } else {
                mSpPanZi.degress = elpasedDegress
            }
        }
    }

    /**
     * 将  degress 精简到 [0,360] 范围
     */
    private fun gcdDegress(degress: Float): Float {
        var ret = degress
        while (ret > 360f) {
            ret -= 360f
        }

        while (ret < 0f) {
            ret += 360f
        }
        return ret
    }

    fun updateUI(info: ZhuanPanInfo) {
        // 这里可以确保  onEnter 方法已被调用
        // 1. 更新剩余次数
        if (info.resetCount > 8) {
            mRestLabel.text = "免费次数:${info.resetCount - 8}"
        } else {
            if(AppConfig.isFake){
                mRestLabel.text = "视频抽奖次数:${info.resetCount}次"
            }else{
                mRestLabel.text = "抽奖次数:${info.resetCount}次"
            }
        }

        // 2. 更新领奖状态,播放动画
        val stateLst = info.awardStateLst
        mHb1.udpateState(stateLst[0], info.usedCount)
        mHb2.udpateState(stateLst[1], info.usedCount)
        mHb5.udpateState(stateLst[2], info.usedCount)

        // 3. 更新进度
        mProgress.percent = CoreUtil.clamp01(info.usedCount / 30f)

        isReady = true
    }
}